<template>
  <view class="message-page">
    <view class="message-head">
      <view class="title">消息</view>
      <view class="tip">
        您已阅读{{ messageCount?.readNum ?? 0 }}条， 确认
        {{
          (messageCount?.passNum ?? 0) + (messageCount?.rejectNum ?? 0)
        }}
        条重要信息
      </view>
      <view class="status-tag">
        <!-- !item.src -->
        <view
          v-for="item in tagList"
          :key="item.value"
          class="status-item"
          :class="{ active: type === item.value }"
          @click="changeMessageType(item.value)"
        >
          <image v-if="item.src" :src="item.src"></image>
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>
    <view class="message-list">
      <view class="tab-container">
        <!-- Tab 导航 -->
        <view class="tabs">
          <view
            class="tab-item"
            v-for="item in tabs"
            :key="item.value"
            :class="{ active: currentTab === item.value }"
            @click="switchTab(item.value)"
          >
            <wd-badge
              :modelValue="
                item.value === 1
                  ? messageCount?.waitConfirmNum
                  : messageCount?.isentUnreadNum
              "
            >
              <text style="padding-right: 8px">{{ item.name }}</text>
            </wd-badge>
            <image
              v-if="currentTab === item.value"
              src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/title-underline.png"
            ></image>
          </view>
        </view>

        <!-- Tab 下 list 内容区域 -->
        <view class="tab-content">
          <view
            class="list-item"
            v-for="item in list"
            :key="item.msgId"
            @click="handleDetail(item?.msgId)"
          >
            <wd-badge
              :is-dot="getStatusFull(item.status) == 'UNREAD'"
              :top="3"
              :right="3"
            >
              <view class="item-head">
                <view>
                  <!-- 消息类型，1--合同，2--设计，3--施工，4--其他,为空则查所有 src="../../static/message/other.png"-->
                  <image
                    class="type-icon"
                    :src="tagList[item.msgType]?.src"
                  ></image>
                  <text class="title">{{ item.msgTitle }}</text>
                  <text
                    v-if="getStatusFull(item.status) !== 'UNREAD'"
                    class="is-read"
                    >已读</text
                  >
                </view>
                <text
                  class="status"
                  v-if="
                    getTypeFull(item.noticeType) == 'VIEWTOCONFIRMREJECTION'
                  "
                  :class="{
                    toConfirmed:
                      (getTypeFull(item.noticeType) ==
                        'VIEWTOCONFIRMREJECTION' &&
                        getStatusFull(item.status + 1) ==
                          'VIEWED_PENDING_CONFIRMATION') ||
                      getStatusFull(item.status) ==
                        'VIEWED_PENDING_CONFIRMATION',
                    confirmed: getStatusFull(item.status) == 'CONFIRMED' || getStatusFull(item.status) == 'AGREED',
                    refuse: getStatusFull(item.status) == 'REJECTED',
                  }"
                  >{{
                    getTypeFull(item.noticeType) == "VIEWTOCONFIRMREJECTION" &&
                    getStatusFull(item.status + 1) ==
                      "VIEWED_PENDING_CONFIRMATION"
                      ? getStatusLabel(item.status + 1)
                      : getStatusLabel(item.status)
                  }}</text
                >
                <!-- noticeType参数为3时， status为1 状态为未查看， 但是也要显示未确认状态（status+1） -->
              </view>
            </wd-badge>
            <view class="item-center">
              {{ item.msgDescription }}
            </view>
            <view class="item-bottom">
              <text class="user">{{ item.sendName }}</text>
              <view class="time">{{ item.date }} <text v-if="item.autoConfirmTime">·</text> <text class="auto-confirm" v-if="item.autoConfirmTime">{{item.autoConfirmTime}}天后自动确认</text> </view>
            </view>
          </view>
          <wd-loadmore v-if="state" :state="state" @reload="reload" />
        </view>
        <Empty v-if="!list?.length" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import Empty from "@/components/empty/index.vue";
import useUserStore from "@/store/modules/user/index.js";
import { onReachBottom, onShow } from "@dcloudio/uni-app";
import { messageList } from "@/api/user";
import { debounce } from "lodash";
const {
  tagList,
  getTypeFull,
  getStatusFull,
  getStatusLabel,
  messageCount,
  getMessageQuantity,
} = useUserStore();
const state = ref("loading");
const query = reactive({
  size: 5,
  current: 1,
});
const list = ref([]);
const total = ref(0);
const test = ref([])
const assemblyData = (data) => {
  return data.map((item) => {
    const [datePart, timePart] = item?.createTime.split(" "); // "2024-11-02 16:11:18"
    const newItem = {
      ...item,
      date: datePart,
    };
    return newItem;
  });
};
const getMessageList = async () => {
  if (total.value > list.value.length) {
    state.value = "loading";
  }
  try {
    const res = await messageList({
      msgType: type.value || "", //消息类型，1--合同，2--设计，3--施工，4--其他,为空则查所有
      viewType: currentTab.value || "",
      ...query,
    });
    const data = res.data.records || [];
    const returnData = assemblyData(data);
    list.value = [...list.value, ...returnData];
    total.value = res.data.total;
    if (!list.value.length) state.value = "empty";
    else if (total.value == list.value.length) state.value = "finished";
  } catch (error) {
    state.value = "error";
  }
};

const reload = debounce(() => {
  if (state.value === "finished" || state.value === "error") return;
  if (list.value.length < total.value) {
    query.current += 1;
    getMessageList();
  }
}, 300);
onShow(() => {
  query.size = 5;
  query.current = 1;
  list.value = [];
  getMessageQuantity(type.value || "");
  getMessageList();
  test.value = [
    {msgTitle:'设计方案跳转',status:1,msgId:1,msgType:1,noticeType:1,msgDescription:'描述',sendName:'张三',date:'2023-10-19'},
  ]

});
// onReachBottom事件实现滚动到底部加载更多
onReachBottom(() => {
  reload();
});
const handleDetail = (msgId) => {
  uni.navigateTo({
    url: `/pages/messageManage/detail/detail?id=${msgId}`,
  });
};
const type = ref(0);
const changeMessageType = (value) => {
  type.value = value;
  getMessageQuantity(type.value);
  query.size = 5;
  query.current = 1;
  list.value = [];
  getMessageList();
};
// 定义 Tab 数据
const tabs = ref([
  {
    name: "我收到的",
    value: 1,
  },
  {
    name: "我发起的",
    value: 2,
  },
]);
// 当前激活的 Tab 索引
const currentTab = ref(1);
// 切换 Tab 函数
const switchTab = (index) => {
  currentTab.value = index;
  query.size = 5;
  query.current = 1;
  list.value = [];
  getMessageList();
};
</script>

<style lang="scss" scoped>
@import "list";
</style>
